<style lang="less" scoped>

.order-detail {
    padding: 15px;
    > .row {
        background-color: #fff;
        padding-top: 15px;
        padding-bottom: 15px;
        margin-bottom: 20px;
        .order-address-info,
        .order-basic-info {
            border-radius: 0;
            background-color: #fff;
        }
    }
    .state-bar {
        display: flex;
        .state-item,
        .state-item-measure {
            flex-grow: 1;
            position: relative;
            .state-info {
                display: flex;
                flex-flow: column nowrap;
                justify-content: center;
                align-items: center;
                width: 60px;
                .cricle {
                    width: 30px;
                    height: 30px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    background-color: #f1f1f1;
                    border-radius: 50%;
                }
                &:before {
                    position: absolute;
                    content: "";
                    width: 70%;
                    height: 1px;
                    background-color: #f1f1f1;
                    top: 30%;
                    left: 0;
                    margin-left: -75%;
                }
            }
            &:first-child {
                .state-info:before {
                    width: 0;
                }
            }
            &.active {
                .state-info {
                    .cricle {
                        background-color: #37CA73;
                        color: #fff;
                    }
                    color: #37CA73;
                }
            }
        }
        .state-item-measure {
            .state-info {
                &:before {
                    width: 70%;
                    margin-left: -65%;
                }
            }
            &:first-child {
                .state-info {
                    &:before {
                        width: 0;
                    }
                }
            }
        }
    }
    .buttons {
        margin-top: 15px;
    }
    .order-item{
      margin-bottom: 10px;
    }
    .small-product-img{
      width: 50px;
      height: 50px;
    }
    .product-title{
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: block-axis;
      height: 40px;
      margin-left: 10px;
      &, &:active, &:focus, &:hover{
        color: #839ED2;
        text-decoration: none;
      }
    }
    .product-img-title{
      display: flex;
      flex-flow: row nowrap;
      align-items: center;
    }

    .hetong{
      width: 100px;
      height: 150px;
    }
}

</style>

<template>

<div id="orderDetail" class="order-detail">
    <div class="row">
        <div class="col-xs-2">
            订单状态：
        </div>
        <div class="col-xs-10 state-bar">
            <div v-for="(state, index) in orderStates" :class="[ activeIndex(index) ? 'state-item active' : 'state-item', isMeasure ? 'state-item-measure' : '']">
                <div class="state-info">
                    <div class="cricle">
                        {{index + 1}}
                    </div>
                    {{state.name}}
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-xs-12">
            <h4>我的订单</h4>
            <div class="well order-basic-info">
                <div class="row">
                    <div class="col-xs-3">
                        <h5>订单编号：<span class="text-gray">{{order.order_no}}</span></h5>
                        <span>{{order.new_date}}</span>
                    </div>
                    <div class="col-xs-3 text-right">
                        <h5 class="text-red">￥{{order.total_money}}</h5>
                        <span v-show="!orderMoneyTip">应付总额</span>
                        <span v-show="orderMoneyTip">已付测量费</span>
                    </div>
                    <div class="col-xs-3 text-center">
                        <h5>订单状态</h5>
                        <span>{{orderWorkFlowState}}</span>
                    </div>
                    <div class="col-xs-3 buttons text-right" v-if="isShowContract()">
                        <!-- <button type="button" name="button" class="btn btn-default" v-show="isShowCancel">取消订单</button>
                        <button type="button" name="button" class="btn btn-primary" v-show="isShowPay">立即付款</button>
                        <button type="button" name="button" class="btn btn-primary" v-show="isShowDownload">立即付款</button> -->
                        <button type="button" name="button" class="btn btn-primary" @click="fileClick">
                          <i class="fa fa-upload"></i>
                          上传合同
                        </button>
                        <input type="file" ref="fileInput" class="hidden" @change="uploadFile"/>
                    </div>
                </div>

                <hr>

                <div class="row order-item" v-if="order.all_order_items && !isMeasure"  v-for="orderItem in order.all_order_items">
                  <div class="col-xs-5 product-img-title">
                      <img :src="productImg(orderItem.item_product)" alt="" class="small-product-img">
                      <a class="product-title" :href="'/products/' +  orderItem.item_product.id">{{orderItem.item_product.title}}</a>
                  </div>
                  <div class="col-xs-2">
                    单价：<span class="text-red">￥{{orderItem.unit_price}}</span>
                  </div>
                  <div class="col-xs-2">
                    数量：{{orderItem.quantity}}
                  </div>
                  <div class="col-xs-3">
                    总价：<span class="text-red">￥{{priceConvert(orderItem.quantity * orderItem.unit_price)}}</span>
                  </div>
                </div>
            </div>

            <h4 v-if="isMeasure">订单流程</h4>
            <div class="row" v-if="isMeasure">
                <div class="col-xs-12">
                  <ul class="list-group">
                    <li class="list-group-item" style="border-radius: 0;" v-for="(history, index) in orderHistories">
                      您在 <span class="text-gray" v-text="parseDate(history.created_at)"></span>
                      <span v-text="history.status != 'unpaid' && history.status != 'survey_completed' ? '支付了' : '需支付'"></span>
                      <span class="text-red" v-text="history.amount"></span>,
                      现在订单状态为：<span class="text-green" v-text="getStatusStr(history.status)"></span>
                      <br>
                      <div class="" style="margin-top: 10px;" v-if="history.content">
                        <a v-for="(paper, index) in history.content" :href="paper" target="_blank"><img style="margin-bottom: 5px; margin-right: 5px;" width="100px;" height="100px;" :src="paper" alt=""></a>
                      </div>
                    </li>
                  </ul>
                </div>
            </div>

            <h4>收货信息</h4>
            <div class="well order-address-info">
                <div class="row">
                    <div class="col-xs-12" v-if="order.full_address">
                        <h5>
                    <label for="">姓名：</label>
                    {{order.full_address.contact_name}}
                  </h5>
                        <h5>
                    <label for="">手机号：</label>
                    {{order.full_address.cellphone}}
                  </h5>
                        <h5>
                    <label for="">地址：</label>
                    {{order.full_address.province}} {{order.full_address.city}} {{order.full_address.district}} {{order.full_address.street}}
                  </h5>
                    </div>
                </div>
            </div>

            <h4 v-if="!isMeasure">发票信息</h4>
            <div class="well order-address-info" v-if="!isMeasure">
                <div class="row">
                    <div class="col-xs-12" v-if="order.full_address">
                        <h5>
                    <label for="">发票信息：</label>
                    {{order.full_address.contact_name}}
                  </h5>
                        <h5>
                    <label for="">发票抬头：</label>
                    {{order.full_address.cellphone}}
                  </h5>
                        <h5>
                    <label for="">发票内容：</label>
                    {{order.full_address.province}} {{order.full_address.city}} {{order.full_address.district}} {{order.full_address.street}}
                  </h5>
                    </div>
                </div>
            </div>

            <h4 v-if="attachmentImg">合同照片</h4>
            <div class="well order-address-info" v-if="attachmentImg">
                <div class="row">
                  <div class="col-xs-12">
                    <img v-bind:src="attachmentImg" alt="" class="hetong">
                  </div>
                </div>
            </div>
        </div>
    </div>
</div>

</template>

<script>
import Util from '../util'
import SuccessDialog from 'success_alert'
import ErrorDialog from 'error_alert'
import Query from '../query'
import Dateformat from 'dateformat'
import _ from 'lodash'
import designImg from '../../../assets/images/new-home/cuxiao-3.png'

export default {
    name: "orderDetail",
    props: {
        myOrder: {
            required: true,
            type: Object
        },
        myOrderHistories: {
          required: true,
          type: Array
        }
    },

    data: function data() {
        return {
            testImg: designImg,
            order: this.myOrder,
            orderHistories: this.myOrderHistories,
            measureStates: [{
                name: '待付款',
                code: 'unpaid'
            }, {
                name: '等待测量',
                code: 'survey_pending'
            }, {
                name: '已测量，待付尾款',
                code: 'survey_completed'
            }, {
                name: '已付尾款，定制生产',
                code: 'tail_payment'
            }, {
                name: '待安装',
                code: 'install_pending'
            }, ],
            CommonStates: [{
                name: '待付款',
                code: 'unpaid'
            }, {
                name: '已付款',
                code: 'paid'
            }],
            heToneImage: null,
            attachmentImg: null,
        }
    },

    mounted: function mounted() {
      let img = this.order.attachment_img
      if (img) {
        this.attachmentImg = img.image.url
      } else {
        this.attachmentImg = false
      }
      console.log(this.orderHistories);
    },

    computed: {
        orderStates: function() {
            var states = []

            if (this.order.order_type === 'normal') {
                states = this.CommonStates
            } else {
                states = this.measureStates
            }

            if (this.order.workflow_state === 'failed') {
                states.push({
                    name: '订单关闭',
                    code: 'failed'
                })
            } else {
                states.push({
                    name: '订单完成',
                    code: 'completed'
                })
            }
            return states
        },

        orderMoneyTip: function() {
          return this.order.workflow_state === 'survey_pending'
        },

        isMeasure: function() {
            if (this.order.order_type === 'surveying') {
                return true
            } else {
                return false
            }
        },

        orderWorkFlowState: function() {
            let states = this.measureStates.concat([{
                name: '已付款',
                code: 'paid'
            }, {
                name: '订单关闭',
                code: 'failed'
            }, {
                name: '订单完成',
                code: 'completed'
            }])

            let filterResurce = states.filter((item) => {
                return item.code === this.order.workflow_state
            })

            return filterResurce[0].name
        },

        isShowCancel: function() {
            if (['unpaid', 'survey_pending'].indexOf(this.order.workflow_state) != -1) {
                return true
            } else {
                return false
            }
        },
        isShowPay: function() {
            if (['unpaid'].indexOf(this.order.workflow_state) != -1) {
                return true
            } else {
                return false
            }
        },
        isShowDownload: function() {
            if (['survey_completed'].indexOf(this.order.workflow_state) != -1) {
              return true
            } else {
              return false
            }
        }
    },

    methods: {
        activeIndex: function(index) {
            var _this = this
            var activeIndex = 0;
            this.orderStates.forEach(function(state, index) {
                if (state.code === _this.order.workflow_state) {
                    activeIndex = index
                }
            })
            if (index <= activeIndex) {
                return true
            } else {
                return false
            }
        },

        // goToZoomed: function(url) {
        //   window.open(url, '_blank')
        // },

        productImg: function(product) {
          return Util.productImg(product)
        },

        priceConvert: function(price) {
          return String(price) + '.0'
        },

        fileClick: function() {
          var fileInput = this.$refs.fileInput
          fileInput.click()
        },

        parseDate: function(date) {
          return Dateformat(date, 'yyyy-mm-dd')
        },

        getStatusStr: function(code) {
          return _.find(this.measureStates, function(item) {
                    return item['code'] == code
                  })['name']
        },
        isShowContract: function() {
          if (['survey_completed','tail_payment'].indexOf(this.order.workflow_state) != -1) {
            return true
          } else {
            return false
          }
        },
        uploadFile: function(e) {
          var image = new Image()
          var _this = this
          var files = e.target.files || e.dataTransfer.files

          if (!files.length) {
            ErrorDialog.show('网络问题，请重新选择图片')
            return
          }

          if(typeof FileReader==='undefined'){
            ErrorDialog.show('您的浏览器不支持图片上传，请升级您的浏览器')
            return
          }

          var reader = new FileReader()
          reader.readAsDataURL(files[0])

          reader.onload = function(e){
            _this.heToneImage = e.target.result
            Query.post('/orders/' + _this.order.id + '/create_contract_img', {
              image: _this.heToneImage
            }).then((data) => {
              if (data.status === 'ok') {
                _this.attachmentImg = data.attachment.image.url
                SuccessDialog.show('合同上传成功！')
              } else {
                SuccessDialog.show('网络问题，请重试！')
              }
            }).catch((error) => {
            })
          }
        },
    }
}

</script>
